# pagination.py
# from django.utils.safestring import mark_safe
# django为了安全会默认拒绝渲染后端的html代码，所以我们需要mark_safe()给html代码标记为安全，才可以在前端渲染

# 输入查询页数，每页数量，列表
class PageNumberPagination:

    def __init__(self, list_all, page_curr = 1, num_per_page = 10):
        # 每页展示的记录数量
        self.num_per_page = num_per_page
        # 当前页数
        self.page_curr = page_curr

        # 总记录数量
        list_sum = list_all.count()
        # 记录范围首记录
        list_start = (page_curr - 1) * num_per_page
        # 记录范围尾记录
        list_end = list_start + num_per_page
        # 展示记录
        self.list_show = list_all[list_start: list_end+1]
        
        # 总页数
        self.page_sum = list_sum // num_per_page + 1
        # 查询范围首页
        page_start = max(1, min(page_curr - num_per_page//2, self.page_sum - num_per_page))
        # 查询范围尾页
        page_end = min(page_start + num_per_page, self.page_sum)
        # 查询范围
        self.page_range = range(page_start, page_end+1)
        
        # 下一页
        self.page_next = min(page_end, page_curr+1)
        # 上一页
        self.page_last = max(1, page_curr-1)

    # def page_form(self):
    #     html_code = f'''<ul class="pagination">'''
    #     html_code += f'''<li><a href="?page=1" aria-label="Previous"><span aria-hidden="true">«</span></a></li>'''
    #     html_code += f'<li><a href="?page='+str(self.page_last)+f'aria-label="Previous"><span aria-hidden="true">/<</span></a></li>'
    #     for page_num in self.page_range:
    #         if page_num == self.page_curr:
    #             html_code += f'<li class="active"><a href="?page='+str(page_num)+f'">'+str(page_num)+'</a></li>'
    #         else:
    #             html_code += f'<li><a href="?page='+str(page_num)+f'">'+str(page_num)+'</a></li>'
    #     html_code += f'<li><a href="?page='+str(self.page_next)+f'" aria-label="Next"><span aria-hidden="true">/></span></a></li>'
    #     html_code += f'<li><a href="?page='+str(self.page_sum)+f'" aria-label="Next"><span aria-hidden="true">»</span></a></li>'
    #     html_code += f'</ul>'
    #
    #     return mark_safe(html_code)